package com.ken.common.event.plugins.idempotent.token;

import com.ken.common.event.framework.message.EventMessage;
import com.ken.common.event.framework.processor.idempotent.handler.IdempotentHandler;
import com.ken.common.event.plugins.idempotent.token.constant.TokenConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * Token幂等性校验器
 */
@Slf4j
@Component
@Primary
public class TokenIdempotentHandler implements IdempotentHandler {

    //lua脚本
    String msgIdLua = "local msgId = KEYS[1]\n" +
            "local key = '" + TokenConstant.TOKEN_REDIS_PREFIX + "'..msgId\n" +
            "local hashKey = redis.call('exists', key)\n" +
            "--判断消息是否存在\n" +
            "if hashKey == 0 then\n" +
            "  return -1\n" +
            "end \n" +
            "--消息id存在,则删除该消息\n" +
            "redis.call('del', 'key')\n" +
            "return 1";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean isIdempotent(EventMessage eventMessage) {
        log.debug("[Msg-Handle] - Token幂等处理器触发 - {}", eventMessage.getMsgId());
        //获得消息id
        String msgId = eventMessage.getMsgId();
        //执行脚本
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<>(msgIdLua, Long.class),
                Collections.singletonList(msgId));
        log.debug("[Msg-Handle] - Token幂等处理器校验结果 - {}", result == 1);
        //判断是否存在
        if (result == 1) {
            return true;
        }
        return false;
    }
}
